package com.tsingteng.cosfun.ui.cosfun;

import android.annotation.SuppressLint;
import android.app.Service;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dingmouren.layoutmanagergroup.viewpager.OnViewPagerListener;
import com.dingmouren.layoutmanagergroup.viewpager.ViewPagerLayoutManager;
import com.pili.pldroid.player.IMediaController;
import com.pili.pldroid.player.PLOnErrorListener;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.AwkwardBean;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.ui.cosfun.adapter.AwkwardAdapter;
import com.tsingteng.cosfun.ui.cosfun.contract.AwkwardContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.presenter.AwkwardPresenter;
import com.tsingteng.cosfun.utils.AVOptionsUtil;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.widget.HeartView;
import com.tsingteng.cosfun.widget.MyRecycleView;

import java.util.ArrayList;
import java.util.List;

public class AwkwardFragment extends BasePresenterFragment<AwkwardPresenter, AwkwardContract.IAwkwardView> implements ObserverListener, AwkwardContract.IAwkwardView, AwkwardAdapter.OnItemClickLisenter, IMediaController {
    private String TAG = this.getClass().getSimpleName();
    private RecyclerView recyclerView = null;
    private ViewPagerLayoutManager mLayoutManager;
    private AwkwardAdapter mAdapter;
    private int pageNo = 1;
    private int currentPosition = 0;
    private int currentVideoId = 0;//当页数据对应的作品id
    private int lastVideoId = 0;//最新作品id
    private List<AwkwardBean.Awkward> videoList = null;
    private AudioManager audio = null;
    private ProgressBar progressBar = null;
    private ProgressBar v_progressBar = null;
    private IMediaController.MediaPlayerControl mPlayer;
    private static final int SHOW_PROGRESS = 2;

    @Override
    protected void initView() {
        super.initView();
        videoList = new ArrayList<>();
        recyclerView = rootView.findViewById(R.id.awkward_list);
        progressBar = rootView.findViewById(R.id.play_progress);
        v_progressBar = rootView.findViewById(R.id.volume_progress);
        mLayoutManager = new ViewPagerLayoutManager(getActivity(), OrientationHelper.VERTICAL);
        mAdapter = new AwkwardAdapter(getActivity(), videoList, this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
        initListener();
        ObserverManager.getInstance().add(this);
        audio = (AudioManager) getActivity().getSystemService(Service.AUDIO_SERVICE);
    }

    private void initListener() {
        mLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {


            @Override
            public void onPageRelease(boolean isNext, int position) {
                int index = 0;
                if (isNext) {
                    index = 0;
                } else {
                    index = 1;
                }
                releaseVideo(index);
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                currentPosition = position;
                playVideo(position);
            }

            @Override
            public void onLayoutComplete() {
            }

        });
    }

    public void getData() {
        if (currentVideoId != lastVideoId) {
            currentVideoId = lastVideoId;
            currentVideoId = 1;
            if (mPresenter != null)
                mPresenter.getAwkwardList(pageNo + "", Config.PAGE_SIZE + "", currentVideoId + "");
        }
    }

    public void playVideo(int position) {
        if (position != -1) {
            currentPosition = position;
        }
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            Log.e("test12", "return");
            return;
        }
        Log.e("test12", "next");
        AwkwardBean.Awkward awkward = videoList.get(currentPosition);
        final PLVideoTextureView videoMain = itemView.findViewById(R.id.awkward_item_view_video_main);
        videoMain.setAVOptions(AVOptionsUtil.getAVOptions());
        videoMain.setLooping(true);
        videoMain.setVideoPath(awkward.getVideoUrl());
        videoMain.setOnInfoListener(mOnInfoListener);
        videoMain.setOnErrorListener(mOnErrorListener);
        videoMain.setMediaController(this);
        videoMain.start();
    }

    public void releaseVideo(int index) {
        View itemView = recyclerView.getChildAt(index);
        if (itemView == null) {
            return;
        }
        final PLVideoTextureView videoMian = itemView.findViewById(R.id.awkward_item_view_video_main);
        final ImageView imgPlay = itemView.findViewById(R.id.awkward_item_view_play);
        if (videoMian != null)
            videoMian.pause();
        progressBar.setProgress(0);
    }

    public void pauseVideo() {
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        final PLVideoTextureView videoMian = itemView.findViewById(R.id.awkward_item_view_video_main);
        final ImageView imgPlay = itemView.findViewById(R.id.awkward_item_view_play);
        videoMian.pause();

    }

    private PLOnInfoListener mOnInfoListener = new PLOnInfoListener() {
        @Override
        public void onInfo(int what, int extra) {
            Log.i(TAG, "OnInfo, what = " + what + ", extra = " + extra);
            switch (what) {
                case PLOnInfoListener.MEDIA_INFO_BUFFERING_START:
                    break;
                case PLOnInfoListener.MEDIA_INFO_BUFFERING_END:
                    break;
                case PLOnInfoListener.MEDIA_INFO_VIDEO_RENDERING_START:
                    break;
                case PLOnInfoListener.MEDIA_INFO_AUDIO_RENDERING_START:
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
                    break;
                case PLOnInfoListener.MEDIA_INFO_VIDEO_FRAME_RENDERING:
                    Log.i(TAG, "video frame rendering, ts = " + extra);
                    break;
                case PLOnInfoListener.MEDIA_INFO_AUDIO_FRAME_RENDERING:
                    Log.i(TAG, "audio frame rendering, ts = " + extra);
                    break;
                case PLOnInfoListener.MEDIA_INFO_VIDEO_GOP_TIME:
                    Log.i(TAG, "Gop Time: " + extra);
                    break;
                case PLOnInfoListener.MEDIA_INFO_SWITCHING_SW_DECODE:
                    Log.i(TAG, "Hardware decoding failure, switching software decoding!");
                    break;
                case PLOnInfoListener.MEDIA_INFO_METADATA:
                    break;
                case PLOnInfoListener.MEDIA_INFO_VIDEO_BITRATE:
                case PLOnInfoListener.MEDIA_INFO_VIDEO_FPS:
//                    updateStatInfo();
                    break;
                case PLOnInfoListener.MEDIA_INFO_CONNECTED:
                    Log.i(TAG, "Connected !");
                    break;
                case PLOnInfoListener.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
                    Log.i(TAG, "Rotation changed: " + extra);
                default:
                    break;
            }
        }
    };
    private PLOnErrorListener mOnErrorListener = new PLOnErrorListener() {
        @Override
        public boolean onError(int errorCode) {
            Log.e(TAG, "Error happened, errorCode = " + errorCode);
            switch (errorCode) {
                case PLOnErrorListener.ERROR_CODE_IO_ERROR:
                    /**
                     * SDK will do reconnecting automatically
                     */
                    Log.e(TAG, "IO Error!");
                    return false;
                case PLOnErrorListener.ERROR_CODE_OPEN_FAILED:
                    Log.i(TAG, "failed to open player !");
                    break;
                case PLOnErrorListener.ERROR_CODE_SEEK_FAILED:
                    Log.i(TAG, "failed to seek !");
                    break;
                default:
                    Log.i(TAG, "unknown error !");
                    break;
            }
            return true;
        }
    };

    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_awkward;
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseVideo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseVideo(0);
    }

    @Override
    protected void initData(View rootView) {

    }

    @Override
    protected AwkwardPresenter createPresenter() {
        return new AwkwardPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return null;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        return null;
    }

    @Override
    protected void refresh() {

    }

    public void changeId(int id) {
        lastVideoId = id;
    }

    @Override
    public void observerUpData(int eventType, int index, int id) {
        switch (eventType) {
            case ObserverListener.EVENT_CHANGE_OPUS:
                lastVideoId = id;
                break;
//            case ObserverListener.EVENT_OPUS_VIDEO_PAUSE:
//                pauseVideo();
//                break;
//            case ObserverListener.EVENT_OPUS_VIDEO_START:
//                playVideo(currentPosition);
//                break;
            case ObserverListener.KEYCODE_VOLUME_UP://音量加
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND);
                int max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                int cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
            case ObserverListener.KEYCODE_VOLUME_DOWN://音量减
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND);
                max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }

    @Override
    public void successStatus() {

    }

    @Override
    public void succeed(AwkwardBean awkwardBean) {
        videoList.addAll(awkwardBean.getData());
        mAdapter.notifyDataSetChanged();
        Log.e("test21", "videoList.size()=" + videoList.size());
    }

    @Override
    public void failure(int code, String error) {

    }

    @Override
    public void playFirst(int position, PLVideoTextureView p1, PLVideoTextureView p2) {
        AwkwardBean.Awkward awkward = videoList.get(position);
//        p1.setAVOptions(AVOptionsUtil.getAVOptions());
        p1.setLooping(true);
        Log.e("test21", "playFirst  position=" + position);
        p1.setOnInfoListener(mOnInfoListener);
        p1.setOnErrorListener(mOnErrorListener);
        p1.setMediaController(this);
        p1.start();
    }

    @Override
    public void setMediaPlayer(MediaPlayerControl mediaPlayerControl) {
        mPlayer = mediaPlayerControl;
    }

    @Override
    public void show() {

    }

    @Override
    public void show(int i) {

    }

    @Override
    public void hide() {

    }

    @Override
    public boolean isShowing() {
        return false;
    }

    @Override
    public void setEnabled(boolean b) {

    }

    @Override
    public void setAnchorView(View view) {

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    if (mPlayer == null || !mPlayer.isPlaying()) {
                        return;
                    }
                    pos = setProgress();
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
                    break;
                case 100:
                    if (v_progressBar != null && v_progressBar.getVisibility() == View.VISIBLE) {
                        v_progressBar.setVisibility(View.INVISIBLE);
                    }
                    break;
            }
        }
    };

    private long setProgress() {
        if (mPlayer == null) {
            Log.e("test21", "mPlayer=null");
            return 0;
        }

        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        if (progressBar != null) {
            if (duration > 0) {
                progressBar.setProgress((int) position);
                progressBar.setMax((int) duration);
            }
        }
        return position;
    }


    boolean sharkFlag = false;

    //摇一摇
    public void shark() {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        sharkFlag = !sharkFlag;

        if (mAdapter != null) {
            mAdapter.setSharkFlag(sharkFlag);
        }
        LogUtils.e("shark", "OpusFragment sharkFlag=" + sharkFlag);
        TextView likeView = itemView.findViewById(R.id.opus_item_view_like);
        TextView tv_comment = itemView.findViewById(R.id.opus_item_view_comment);
        TextView tv_share = itemView.findViewById(R.id.opus_item_view_share);
        RelativeLayout rl_awkward = itemView.findViewById(R.id.opus_item_view_awkward_rel);
//        HeartView heartView = itemView.findViewById(R.id.opus_item_view_video_heartView);
        if (sharkFlag) {
            likeView.setVisibility(View.VISIBLE);
            tv_comment.setVisibility(View.VISIBLE);
            tv_share.setVisibility(View.VISIBLE);
            rl_awkward.setVisibility(View.VISIBLE);
//            heartView.setVisibility(View.VISIBLE);
        } else {
            likeView.setVisibility(View.GONE);
            tv_comment.setVisibility(View.GONE);
            tv_share.setVisibility(View.GONE);
            rl_awkward.setVisibility(View.GONE);
//            heartView.setVisibility(View.INVISIBLE);
        }

    }

}
